package com.glela.live.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.glela.api.im.util.IMConfig;
import com.glela.cache.model.RedisKey;
import com.glela.cache.redis.RedisKeys;
import com.glela.cache.redis.RedisUtil;
import com.glela.common.util.Config;
import com.glela.common.util.JsonUtil;
import com.glela.live.mapper.LiveAudienceCountMapper;
import com.glela.live.mapper.LiveUserRecordMapper;
import com.glela.live.messages.*;
import com.glela.live.model.LiveAudienceCount;
import com.glela.live.model.LivePlan;
import com.glela.live.model.LiveUserRecord;
import com.glela.live.models.*;
import com.glela.live.service.ChatRoomService;
import com.glela.live.service.LivePlanService;
import com.glela.live.util.LiveConfig;
import com.glela.live.util.RandomCharUtil;
import com.glela.live.util.RongCloud;
import com.glela.platform.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.naming.Name;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class ChatRoomServiceImpl implements ChatRoomService {

	@Autowired
	protected RedisUtil redisUtil;

	@Autowired
	private UserService userService;

	@Autowired
    private LivePlanService livePlanService;

	@Autowired
	private LiveAudienceCountMapper liveAudienceCountMapper;
	
	@Autowired
	private LiveUserRecordMapper liveUserRecordMapper;

	@Override
	public String createChatRoom(JSONObject jsonObject) {
		// 创建聊天室方法
		ChatRoomInfo[] chatroomCreateChatRoomInfo = { new ChatRoomInfo(jsonObject.getString("liveUserId"),
				jsonObject.getString("roomName") == null ? "" : jsonObject.getString("roomName")) };
		CodeSuccessResult chatroomCreateResult = null;
		try {
			chatroomCreateResult = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).chatroom
					.create(chatroomCreateChatRoomInfo);
		} catch (Exception e) {
			return JsonUtil.getFailJsonStr("创建聊天室失败");
		}
		// 聊天室保活
		// RongCloud.getInstance(IMConfig.appKey,
		// IMConfig.appSecret).chatroom.keepLive(jsonObject.getString("liveUserId"));
		return JsonUtil.getSuccessJsonStr("ok", chatroomCreateResult);
	}

	@Override
	public String queryChatRoom(JSONObject jsonObject) {
		String[] chatroomQueryChatroomId = { jsonObject.getString("liveUserId") };
		try {
			ChatroomQueryResult chatroomQueryResult = RongCloud.getInstance(IMConfig.appKey,
					IMConfig.appSecret).chatroom.query(chatroomQueryChatroomId);
			if (chatroomQueryResult.getChatRooms().isEmpty()) {
				return JsonUtil.getFailJsonStr("未查询到该聊天室信息");
			}
			return JsonUtil.getSuccessJsonStr("ok", chatroomQueryResult);
		} catch (Exception e) {
			return JsonUtil.getFailJsonStr("获取聊天室信息失败");
		}
	}

	@Override
	public String joinChatRoom(JSONObject jsonObject) {
		try {
			String[] chatroomJoinUserId = { jsonObject.getString("userId") };
			CodeSuccessResult chatroomJoinResult = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).chatroom
					.join(chatroomJoinUserId, jsonObject.getString("liveUserId"));
			return JsonUtil.getSuccessJsonStr("ok", chatroomJoinResult);
		} catch (Exception e) {
			return JsonUtil.getFailJsonStr("加入聊天室失败");
		}

	}

	@Override
	public String getToken(JSONObject jsonObject) {
		try {
			Long uid = jsonObject.getLongValue("userId");
			JSONObject result = new JSONObject();
			if (StringUtils.isNotBlank(redisUtil.hget(RedisKeys.IM_USER_TOKEN, uid + ""))) {
//				result.put("code", 200);
				result.put("token", redisUtil.hget(RedisKeys.IM_USER_TOKEN, uid + ""));
			} else {
				com.glela.platform.model.User user = userService.getUserById(jsonObject.getLongValue("userId"));
				TokenResult userGetTokenResult = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).user
						.getToken(jsonObject.getString("userId"), user==null?"":user.getNickName(), user==null?"":user.getPicture());
//				result.put("code", 200);
				result.put("token", userGetTokenResult.getToken());
				redisUtil.hmset(RedisKeys.IM_USER_TOKEN, uid + "", userGetTokenResult.getToken());
			}
			return JsonUtil.getSuccessJsonStr("ok", result);
		} catch (Exception e) {
			return JsonUtil.getFailJsonStr("获取聊天室token失败");
		}

	}

	@Override
	public String queryRoomUsers(JSONObject jsonObject) {
		/*try {
			JSONObject result = new JSONObject();
			if (StringUtils.isNotBlank(
					redisUtil.get(RedisKeys.LIVE_USER_COUNT + jsonObject.getString("liveUserId") + ":exp"))) {
				String counts = redisUtil.get(RedisKeys.LIVE_USER_COUNT + jsonObject.getString("liveUserId"));
				String liveCountNumber[] = counts.split(",");
				result.put("total", liveCountNumber[0]);
			} else {
				if (StringUtils
						.isNotBlank(redisUtil.get(RedisKeys.LIVE_USER_COUNT + jsonObject.getString("liveUserId")))) {
					String counts = redisUtil.get(RedisKeys.LIVE_USER_COUNT + jsonObject.getString("liveUserId"));
					String liveCountNumber[] = counts.split(",");
					result.put("total", liveCountNumber[0]);
					cacheLiveCountNum(jsonObject.getString("liveUserId"));
				} else {
					ChatroomUserQueryResult chatroomQueryUserResult = RongCloud.getInstance(IMConfig.appKey,
							IMConfig.appSecret).chatroom.queryUser(jsonObject.getString("liveUserId"), "10", "2");
					redisUtil.set(redisUtil.get(RedisKeys.LIVE_USER_COUNT + jsonObject.getString("liveUserId")),
							chatroomQueryUserResult.getTotal());
					redisUtil.set(
							redisUtil.get(RedisKeys.LIVE_USER_COUNT + jsonObject.getString("liveUserId") + ":exp"), "1",
							5);
					result.put("total", chatroomQueryUserResult.getTotal() + "");
				}
			}
			return JsonUtil.getSuccessJsonStr("ok", result);
		} catch (Exception e) {
			return JsonUtil.getFailJsonStr("查询聊天室用户列表失败");
		}*/
        JSONObject result = new JSONObject();
        try {
            ChatroomUserQueryResult chatroomQueryUserResult = RongCloud.getInstance(IMConfig.appKey,
                    IMConfig.appSecret).chatroom.queryUser(jsonObject.getString("liveUserId"), "10", "2");
            result.put("total",chatroomQueryUserResult.getTotal());
            return JsonUtil.getSuccessJsonStr("ok", result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.put("total",0);
        return JsonUtil.getSuccessJsonStr("ok", result);
    }

	private static ExecutorService executorService = Executors.newFixedThreadPool(20);

	public void cacheLiveCountNum(final String key) {
		executorService.submit(new Runnable() {
			@Override
			public void run() {
				ChatroomUserQueryResult chatroomQueryUserResult = null;
				try {
					chatroomQueryUserResult = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).chatroom
							.queryUser(key, "10", "2");
					redisUtil.set(redisUtil.get(RedisKeys.LIVE_USER_COUNT + key), chatroomQueryUserResult.getTotal());
					redisUtil.set(redisUtil.get(RedisKeys.LIVE_USER_COUNT + key + ":exp"), "1", 5);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	public String destroyChartRoom(JSONObject jsonObject) {
		try {
			String[] rooms = { jsonObject.getString("liveUserId") };
			CodeSuccessResult destroyResult = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).chatroom
					.destroy(rooms);
			return JsonUtil.getSuccessJsonStr("ok", destroyResult);
		} catch (Exception e) {
			return JsonUtil.getFailJsonStr("销毁聊天室失败");
		}
	}

	@Override
	public String addGagUser(JSONObject jsonObject) {
		try {
			CodeSuccessResult destroyResult = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).chatroom.addGagUser(jsonObject.getString("userId"),jsonObject.getString("liveUserId"),jsonObject.getString("minute"));
	        return JsonUtil.getSuccessJsonStr("ok",destroyResult);
		} catch (Exception e) {
			return JsonUtil.getFailJsonStr("添加聊天室禁言用户失败");
		}
	}

	@Override
	public String queryGagUser(JSONObject jsonObject) {
		try {
			ListGagChatroomUserResult listGagChatroomUserResult = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).chatroom.ListGagUser(jsonObject.getString("liveUserId"));
	        return JsonUtil.getSuccessJsonStr("ok",listGagChatroomUserResult);
		} catch (Exception e) {
			return JsonUtil.getFailJsonStr("查询聊天室禁言列表失败");
		}

	}

	@Override
	public String rollbackGagUser(JSONObject jsonObject) {
		try {
			CodeSuccessResult rollbackResult = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).chatroom.rollbackGagUser(jsonObject.getString("userId"),jsonObject.getString("liveUserId"));
	        return JsonUtil.getSuccessJsonStr("ok",rollbackResult);
		} catch (Exception e) {
			return JsonUtil.getFailJsonStr("解除聊天室禁言用户失败");
		}

	}

	@Override
	public String stopDistribution(JSONObject jsonObject) {
		try {
            CodeSuccessResult result = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).chatroom.stopDistributionMessage(jsonObject.getString("liveUserId"));
            return JsonUtil.getSuccessJsonStr("ok",result);
        } catch (Exception e) {
            return JsonUtil.getFailJsonStr("停止消息分发失败");
        }
	}

	@Override
	public String resumeDistribution(JSONObject jsonObject) {
		try {
            CodeSuccessResult result = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).chatroom.resumeDistributionMessage(jsonObject.getString("liveUserId"));
            return JsonUtil.getSuccessJsonStr("ok",result);
        } catch (Exception e) {
            return JsonUtil.getFailJsonStr("恢复消息分发失败");
        }
	}

	@Override
	public String publish(JSONObject jsonObject) {
		com.glela.platform.model.User userinfo = userService.getUserById(jsonObject.getLongValue("fromUserId"));
        User user = new User(jsonObject.getString("fromUserId"),userinfo==null?"":userinfo.getNickName(),userinfo==null?"":(Config.getString("qiniu.http.base")+userinfo.getPicture()));
        TxtMessage txtMessage = new TxtMessage(jsonObject.getString("text"),"",user);
        String[] chartRooms = {jsonObject.getString("toChatroomId")};
        try {
            CodeSuccessResult result = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).message.publishChatroom(jsonObject.getString("fromUserId"),chartRooms,txtMessage);
            return JsonUtil.getSuccessJsonStr("ok",result);
        } catch (Exception e) {
            return JsonUtil.getFailJsonStr("发送聊天室消息");
        }
	}

	@Override
	public String randomPublish(JSONObject jsonObject) {
//		com.glela.platform.model.User userinfo = userService.getUserById(jsonObject.getLongValue("fromUserId"));
		String name = "";
		if (LiveConfig.randName.length>0){
			name = LiveConfig.randName[(int)(Math.random()*LiveConfig.randName.length)];
		}else{
			try {
				name = RandomCharUtil.randomNickName((int)(Math.random() * 3));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		//RandomCharUtil.randomNickName((int)(Math.random() * 3));
		User user = new User("-1", name,"");
		TxtMessage txtMessage = new TxtMessage(jsonObject.getString("text"),"",user);
		String[] chartRooms = {jsonObject.getString("toChatroomId")};
		try {
			CodeSuccessResult result = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).message.publishChatroom("-1",chartRooms,txtMessage);
			return JsonUtil.getSuccessJsonStr("ok",result);
		} catch (Exception e) {
			return JsonUtil.getFailJsonStr("发送聊天室消息");
		}
	}

	@Override
	public String publishGift(JSONObject jsonObject) {
		com.glela.platform.model.User userinfo = userService.getUserById(jsonObject.getLongValue("fromUserId"));
		com.glela.live.messages.User user = new com.glela.live.messages.User(jsonObject.getString("fromUserId"),
				userinfo == null ? "" : userinfo.getNickName(),
				userinfo == null ? "" : (Config.getString("qiniu.http.base") + userinfo.getPicture()));
		GiftMessage giftMessage = new GiftMessage("1", "xxxxxxx", "大游艇", user);
		String[] chartRooms = { jsonObject.getString("toChatroomId") };
		try {
			CodeSuccessResult result = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).message
					.publishChatroom(jsonObject.getString("fromUserId"), chartRooms, giftMessage);
			return JsonUtil.getSuccessJsonStr("ok", result);
		} catch (Exception e) {
			return JsonUtil.getFailJsonStr("消息发送失败");
		}
	}

	@Override
	public String fanout(JSONObject jsonObject) {
		com.glela.platform.model.User userinfo = userService.getUserById(jsonObject.getLongValue("fromUserId"));
		com.glela.live.messages.User user = new com.glela.live.messages.User(jsonObject.getString("fromUserId"),
				userinfo == null ? "" : userinfo.getNickName(), userinfo == null ? "" : userinfo.getPicture());
		FanoutMessage fanoutMessage = new FanoutMessage(jsonObject.getString("text"), user);
		try {
			CodeSuccessResult result = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).message
					.fanout(jsonObject.getString("fromUserId"), fanoutMessage);
			return JsonUtil.getSuccessJsonStr("ok", result);
		} catch (Exception e) {
			return JsonUtil.getFailJsonStr("发送广播消息失败");
		}
	}

	@Override
	public String history(JSONObject jsonObject) {
		try {
			HistoryMessageResult result = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).message
					.getHistory(jsonObject.getString("date"));
			return JsonUtil.getSuccessJsonStr("ok", result);
		} catch (Exception e) {
			return JsonUtil.getFailJsonStr("获取消息历史记录下载地址失败");
		}
	}

	/*@Override
    public int sendLiveDoneMessage(int liveuserId) {
        //下发LiveDoneMessage消息到聊天室
        LiveDoneMessage liveDoneMessage = new LiveDoneMessage();
        String[] chartRooms = {liveuserId+""};
        try {
            CodeSuccessResult result = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).message.publishChatroom("-1",chartRooms,liveDoneMessage);
            return 1;
        } catch (Exception e) {
        }
        return 0;
    }*/

    @Override
    public int accumulationLikeTotal(int id,long number) {
        return redisUtil.incrBy(RedisKeys.LIVE_PLAN_TOTAL_LIKE_NUM+id,number).intValue();
    }

    @Override
    public int addLiveAudience(int livePlanId) {
//        String likeTotal = redisUtil.get(RedisKeys.LIVE_PLAN_TOTAL_LIKE_NUM+livePlanId)==null?0+"":redisUtil.get(RedisKeys.LIVE_PLAN_TOTAL_LIKE_NUM+livePlanId);
        LivePlan livePlan = livePlanService.getById(livePlanId);
        /*JSONObject json = new JSONObject();
        json.put("liveUserId",livePlan==null?0:livePlan.getLiveuserId());*/
//        String chatUser = queryRoomUsers(json);
		String joinUserNum = redisUtil.get(RedisKeys.LIVE_PLAN_USER_NUMBER+livePlanId);
		//通过app进入的用户统计数
        int userNum = joinUserNum==null?0:Integer.valueOf(joinUserNum);/*JSONObject.parseObject(chatUser).getJSONObject("data").getIntValue("total");*/
		long h5Num = redisUtil.zCount(RedisKey.REDIS_KEY_LIVE_H5_RECORD_SET+livePlanId,System.currentTimeMillis()-(30*1000),System.currentTimeMillis()+1000);
        //存入数据库
		LiveAudienceCount liveAudienceCount = new LiveAudienceCount();
		liveAudienceCount.setLivePlanId(livePlanId);
		liveAudienceCount.setRelCount(userNum+(int)h5Num);
		liveAudienceCount.setShowCount(userNum+(int)h5Num+livePlan.getAddUserNum());
		return liveAudienceCountMapper.add(liveAudienceCount);
		//向聊天室发送总人数消息
//        return sendTotalUserNumber(livePlanId+"",userNum+livePlan.getAddUserNum(),likeTotal==null?0:Integer.valueOf(likeTotal));
    }

    /*@Override
    public int sendStreamMessage(int liveUserId, int status) {
        StreamMessage streamMessage = new StreamMessage(status);
        String[] chartRooms = {liveUserId+""};
        try {
            CodeSuccessResult result = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).message.publishChatroom("-1",chartRooms,streamMessage);
            return 1;
        } catch (Exception e) {
        }
        return 0;
    }*/

	@Override
	public int addLiveUserRecord(int action, int chatRoomUserId, int livePlanId) {
		if(0 == action){    //0:进入直播间 
			redisUtil.incr(RedisKeys.LIVE_PLAN_USER_NUMBER+livePlanId);
		}
		if(1 == action){	//1：离开直播间 
			redisUtil.decr(RedisKeys.LIVE_PLAN_USER_NUMBER+livePlanId);
		}
		return liveUserRecordMapper.add(action,chatRoomUserId,livePlanId);
		
	}

	/*@Override
	public int sendTotalUserNumber(String livePlanId,int showNum,int likeTotal) {
		try {
			ChatRoomDateMessage chatRoomDateMessage = new ChatRoomDateMessage(showNum,likeTotal);
			String[] chartRooms = {livePlanId+""};
			RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).message.publishChatroom("-1",chartRooms,chatRoomDateMessage);
			//System.out.println("=======================下发总人数，总赞数==============耗时"+(System.currentTimeMillis()-time)+"===========当前时间戳："+System.currentTimeMillis());
			return 1;
		} catch (Exception e) {
		}
		return 0;
	}

	@Override
	public int sendOrderMessage(int id,String nickName) {
		try {
			User user = new User("-1","-1","");
			OrderMessage orderMessage = new OrderMessage(nickName,user);
			String[] chartRooms = {id+""};
			RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).message.publishChatroom("-1",chartRooms,orderMessage);
			return 1;
		} catch (Exception e) {
		}
		return 0;
	}*/

	@Override
	public int mngSendMessage(int chatRoomId, BaseMessage baseMessage) {
		String[] chartRooms = {chatRoomId+""};
		try {
			RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).message.publishChatroom("-1",chartRooms,baseMessage);
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public int addBatchUserRecord(List<LiveUserRecord> userRecords) {
		return liveUserRecordMapper.addBatchUserRecord(userRecords);
	}
}
